終於來到第 18 天了,今天來用 react hook 寫個簡易版的計算機吧!
一樣在 codesandbox 中開啟新專案,建立基本的架構
App.js
import "./styles.css";
import Calculator from "./Calculator.js";
export default function App() {
return (
<div className="App">
<Calculator />
</div>
);
}
在這裡寫主要的加減乘除的函式,
Calculator.js
import { useRef, useState, useReducer } from "react";
import CalcButton from "./CalcButton";
import Result from "./Result";
export default function Calculator() {
return (
<div className="calculator-wrap">
<Result content={calcResult.value} />
<div className="d-flex btn-wrap">
<CalcButton action="c" onClick={handleSetZero} />
</div>
<div className="d-flex btn-wrap">
<CalcButton action="7" />
<CalcButton action="8" />
<CalcButton action="9" />
<CalcButton action="/" onClick={handleDivision} />
</div>
<div className="d-flex btn-wrap">
<CalcButton action="4" />
<CalcButton action="5" />
<CalcButton action="6" />
<CalcButton action="*" onClick={handleMultiply} />
</div>
<div className="d-flex btn-wrap">
<CalcButton action="1" />
<CalcButton action="2" />
<CalcButton action="3" />
<CalcButton action="-" onClick={handleMinus} />
</div>
<div className="d-flex btn-wrap">
<CalcButton action="0" />
<CalcButton action="." />
<CalcButton action="=" onClick={handleResult} />
<CalcButton action="+" onClick={handlePlus} />
</div>
</div>
);
}
單純接收 onClick 作為 props 跟顯示按下該按鈕要做什麼動作的 button(child component)
順便寫一下簡單的 regex 判定一下按鈕的樣式
CalcButton.js
export default function CalcButton(props) {
const { onClick, action } = props;
let btnClass = "";
action.match(/\+|-|\*|\/|=/)
? (btnClass = "operator-btn btn")
: action === "c"
? (btnClass = "c-btn btn")
: (btnClass = "number-btn btn");
return (
<button className={btnClass} onClick={onClick}>
{action}
</button>
);
}
顯示運算結果的 component
Result.js
export default function Result(props) {
const { content } = props;
return <div className="calc-result">{content}</div>;
}
先寫一點css讓樣式美觀一點..
style.css
.App {
font-family: sans-serif;
text-align: center;
width: 100%;
}
.calculator-wrap {
background-color: #1d1b1b;
margin: 30px auto;
padding: 15px 20px 30px 20px;
max-width: 640px;
border-radius: 15px;
}
.d-flex {
display: flex;
align-items: center;
justify-content: center;
}
.btn-wrap {
margin: 5px auto;
}
.btn-wrap:nth-of-type(2) {
margin: 15px auto 5px auto;
}
.calc-result {
text-align: right;
padding: 12px 8px 8px 8px;
font-size: 24px;
border-radius: 15px;
background-color: #fff;
}
.btn {
outline: none;
border: 0;
width: 100%;
margin: 5px;
padding: 12px;
font-size: 16px;
border-radius: 5px;
}
.c-btn {
background-color: #00e1ff;
}
.operator-btn {
background-color: #ff3300;
color: #fff;
}
.number-btn {
background-color: #c9c9c9;
}
這時候畫面長這樣..
明天再接續寫處理運算的部分(汗
到目前為止的codesandbox在這裡